//
//  PingJiaViewController.m
//  阿帕
//
//  Created 阿帕 on 2019/12/23.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "PingJiaViewController.h"
#import "TZImagePickerController.h"
#import "ZXCollectionCell.h"
#import "CYPlaceholderTextView.h"

@interface PingJiaViewController ()<AMapLocationManagerDelegate,TZImagePickerControllerDelegate,ZXCollectionCellDelegate, UICollectionViewDataSource,UICollectionViewDelegate>
{
    NSNumber *_hyzsxScore;
    NSNumber *_fksxxScore;
    NSNumber *_addressGrade;///地址准确性
    NSNumber *_loadGrade;///装卸时效性
    NSNumber *_multipleGrade;///综合满意度
    
    NSString *_longitude;
    NSString *_latitude;
}
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic,strong) NSMutableArray *imageArr;
@property (nonatomic,strong) NSMutableArray *imageUrlArray;
@property (nonatomic,strong) UICollectionView *collectionView;
//@property (nonatomic, strong) GQRatingView *ratingView;
@property (strong , nonatomic)CYPlaceholderTextView *textView;

@property (weak, nonatomic) IBOutlet UIView *deFenBgView;
@property (weak, nonatomic) IBOutlet UIButton *faBuButton;

@end

@implementation PingJiaViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _longitude = @"";
    _latitude = @"";
    _hyzsxScore = @5;
    _fksxxScore = @5;
    _addressGrade = @5;
    _loadGrade = @5;
    _multipleGrade = @5;
    
    [self setupBaseView];
}

- (void)setupBaseView {
    
    self.navigationItem.title = @"评价货主";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //    _textField.text = @"";
    //    _textField.textColor = Dark_TextColor;
    //    _textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请填写评价内容" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    //    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    //    _textField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    //    _textField.leftViewMode = UITextFieldViewModeAlways;
    //    [_textField addSubview: leftView];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    lineView.backgroundColor = BackgroundColor;
    [self.view addSubview:lineView];
    
    NSArray *titles = @[@"货物相符性", @"付款时效性", @"地址准确性", @"装卸时效性", @"综合满意度"];
    
    for (int i=0; i<titles.count; i++) {
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10 + 30*i, 80, 30)];
        textLabel.font = font(16);
        textLabel.text = titles[i];
        textLabel.adjustsFontSizeToFitWidth = YES;
        textLabel.textColor = Dark_TextColor;
        [_deFenBgView addSubview:textLabel];
    }
    
    
    //五角星 链式调用 [NSNumber numberWithInt:_model.avgBasicGrade]
    GQRatingView *hyRatingView = [GQRatingView init]
    .frameChain(CGPointMake(100, 15), 20)
    .canTouchChain(YES)
    .needIntValueChain(YES)
    .scoreNumChain(_hyzsxScore)
    .normalColorChain([UIColor cy_colorWithHexString:@"#C0CDDE"])
    .highlightColorChian([UIColor cy_colorWithHexString:@"#FFC000"])
    .scroreBlockChain(^(NSNumber *scoreNumber){
        NSLog(@"%@",scoreNumber);
        _hyzsxScore = scoreNumber;
    }).superViewChain(_deFenBgView);
    
    GQRatingView *fkRatingView = [GQRatingView init]
    .frameChain(CGPointMake(100, 45), 20)
    .canTouchChain(YES)
    .needIntValueChain(YES)
    .scoreNumChain(_fksxxScore)
    .normalColorChain([UIColor cy_colorWithHexString:@"#C0CDDE"])
    .highlightColorChian([UIColor cy_colorWithHexString:@"#FFC000"])
    .scroreBlockChain(^(NSNumber *scoreNumber){
        NSLog(@"%@",scoreNumber);
        _fksxxScore = scoreNumber;
    }).superViewChain(_deFenBgView);
    
    GQRatingView *addressGradeRatingView = [GQRatingView init]
    .frameChain(CGPointMake(100, 75), 20)
    .canTouchChain(YES)
    .needIntValueChain(YES)
    .scoreNumChain(_addressGrade)
    .normalColorChain([UIColor cy_colorWithHexString:@"#C0CDDE"])
    .highlightColorChian([UIColor cy_colorWithHexString:@"#FFC000"])
    .scroreBlockChain(^(NSNumber *scoreNumber){
        NSLog(@"%@",scoreNumber);
        _addressGrade = scoreNumber;
    }).superViewChain(_deFenBgView);
    
    GQRatingView *loadGradeRatingView = [GQRatingView init]
    .frameChain(CGPointMake(100, 105), 20)
    .canTouchChain(YES)
    .needIntValueChain(YES)
    .scoreNumChain(_loadGrade)
    .normalColorChain([UIColor cy_colorWithHexString:@"#C0CDDE"])
    .highlightColorChian([UIColor cy_colorWithHexString:@"#FFC000"])
    .scroreBlockChain(^(NSNumber *scoreNumber){
        NSLog(@"%@",scoreNumber);
        _loadGrade = scoreNumber;
    }).superViewChain(_deFenBgView);
    
    GQRatingView *multipleGradeRatingView = [GQRatingView init]
    .frameChain(CGPointMake(100, 135), 20)
    .canTouchChain(YES)
    .needIntValueChain(YES)
    .scoreNumChain(_multipleGrade)
    .normalColorChain([UIColor cy_colorWithHexString:@"#C0CDDE"])
    .highlightColorChian([UIColor cy_colorWithHexString:@"#FFC000"])
    .scroreBlockChain(^(NSNumber *scoreNumber){
        NSLog(@"%@",scoreNumber);
        _multipleGrade = scoreNumber;
    }).superViewChain(_deFenBgView);
    
    UIView *textBgView = [[UIView alloc] initWithFrame:CGRectMake(15, _deFenBgView.cy_bottom, ScreenW-30, 80)];
    textBgView.backgroundColor = [UIColor cy_colorWithHexString:@"#F3F5F8"];
    [self.view addSubview:textBgView];
    
    _textView = [[CYPlaceholderTextView alloc] initWithFrame:CGRectMake(11, 8, textBgView.cy_width - 22, textBgView.cy_height - 16)];
    _textView.text = @"";
    _textView.textColor = Dark_TextColor;
    _textView.placeholder = @"说说你对本次服务的体验，帮助我们为您提供更好的服务~";
    _textView.placeholderColor = [UIColor cy_colorWithHexString:@"#B6BED2"];
    _textView.backgroundColor = [UIColor cy_colorWithHexString:@"#F3F5F8"];
    _textView.font = font(14);
    [textBgView addSubview:_textView];
    
    [_faBuButton setBackgroundColor:Theme_ColorValue];
    [_faBuButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    cut(_faBuButton, BTN_BORDER_RADIUS);
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    //设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //注册cell和ReusableView（相当于头部）
    [self.collectionView registerClass:[ZXCollectionCell class] forCellWithReuseIdentifier:@"cell"];
            
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textBgView.mas_bottom).offset(20);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(_faBuButton.mas_top).offset(-10);
    }];

}


- (IBAction)fabuEventClick:(id)sender {
    WEAKSELF
    if ([_hyzsxScore isEqual:@0] || [_fksxxScore isEqual:@0] || [_addressGrade isEqual:@0] || [_loadGrade isEqual:@0] || [_multipleGrade isEqual:@0]) {
        [XSInfoView showInfo:@"请先打分" onView:self.view];
        return;
    }
    
    if ([DCSpeedy isBlankString:_textView.text]) {
        [XSInfoView showInfo:@"请填写评价内容" onView:self.view];
        return;
    }
    
    NSString *arrStr = @"";
    
    if (self.imageUrlArray.count != 0) {
        arrStr = [self.imageUrlArray componentsJoinedByString:@","];
    }
    
    NSDictionary *params = @{
        @"orderCode": _orderCode,//运单号
        @"truthGrade": CJStringWithFormat(@"%@", _hyzsxScore),//货源真实性
        @"timeGrade": CJStringWithFormat(@"%@", _fksxxScore),//付款时效性
        @"addressGrade": CJStringWithFormat(@"%@", _addressGrade),//地址准确性
        @"loadGrade": CJStringWithFormat(@"%@", _loadGrade),//装卸时效性
        @"multipleGrade": CJStringWithFormat(@"%@", _multipleGrade),//综合满意度
        @"commentContent": _textView.text,
        @"commentType": @"1",//0-货主给司机打分，1-司机给货主打分
        @"imageUrl": arrStr,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], ORDER_COMMENT) withParameter:params withVC:self netName:@"评价提交" success:^(id response, NSString *msg) {
        
        [XSInfoView showInfo:@"评价成功" onView:self.view];
        
        [KNotificationCenter postNotificationName:YUNDANCENTERLIST_REFRESH object:nil];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArr.count;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    ZXCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    if (!cell) {
        NSLog(@"无法创建CollectionViewCell时打印，自定义的cell就不可能进来了。");
    }
    if (indexPath.item == 0) {
        cell.close.hidden = YES;
    } else {
        cell.close.hidden = NO;
    }
    cell.imgView.image = [self.imageArr objectAtIndex:indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //边距占5*4=20 ，2个
    //图片为正方形，边长：(fDeviceWidth-20)/2-5-5 所以总高(fDeviceWidth-20)/2-5-5 +20+30+5+5 label高20 btn高30 边
    return CGSizeMake((ScreenW-20)/4, (ScreenW-20)/4);
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 5, 5, 5);
}
//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    
    [SystemPermissionsToolObject determineLatestPermissionsOfTheLocalAlbum];
    
    if (indexPath.item == 0) {
        
        if (self.imageArr.count == 10) {
            [XSInfoView showInfo:@"最多可上传9张图片" onView:self.view];
        } else {
            
            [SystemPermissionsToolObject determineLatestPermissionsOfTheLocalAlbum];
            
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
            imagePickerVc.allowPickingVideo = NO;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                [weakSelf.imageArr addObjectsFromArray:photos];
                //            weakSelf.imageArr = [[weakSelf.imageArr reverseObjectEnumerator] allObjects];
                [weakSelf.collectionView reloadData];
                
                [HTTPManager postUploadFiles:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl],FILE_UPLOAD) file:photos fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
                    
                    [weakSelf.imageUrlArray addObject:response[@"data"]];
                    
                } failure:^(NSInteger code, NSString *msg) {
                    
                }];
                
            }];
            imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:imagePickerVc animated:YES completion:nil];
            
        }
        
    } else {
        
        //查看
        HZPhotoBrowser *browser = [[HZPhotoBrowser alloc] init];
        browser.isFullWidthForLandScape = YES;
        browser.isNeedLandscape = YES;
        browser.currentImageIndex = (int)(indexPath.item-1);
        browser.imageArray = weakSelf.imageUrlArray;
        [browser show];
    }
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)moveImageBtnClick:(ZXCollectionCell *)aCell{
    NSIndexPath * indexPath = [self.collectionView indexPathForCell:aCell];
    NSLog(@"删除了第%ld个图片",indexPath.row);
    [self.imageArr removeObjectAtIndex:indexPath.row];
    [self.imageUrlArray removeObjectAtIndex:indexPath.row-1];
    [self.collectionView reloadData];
}
- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置定位超时时间
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    
    //设置允许连续定位逆地理
    [self.locationManager setLocatingWithReGeocode:YES];
    
    [self.locationManager startUpdatingLocation];
}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    
}

#pragma mark - AMapLocationManager Delegate

/**
 *  @brief 连续定位回调函数.注意：如果实现了本方法，则定位信息不会通过amapLocationManager:didUpdateLocation:方法回调。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param location 定位结果。
 *  @param reGeocode 逆地理信息。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    _longitude = CJStringWithFormat(@"%f",location.coordinate.longitude);
    _latitude = CJStringWithFormat(@"%f",location.coordinate.latitude);
    
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.longitude) forKey:LONGITUDE];
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.latitude) forKey:LATITUDE];
    
    //详细信息
    if (reGeocode)
    {
        NSLog(@"reGeocode:%@", reGeocode);
    }
    
}

- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestAlwaysAuthorization];
}

/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    
    DebugLog(@"定位error：%@",error);
}
- (void)dealloc
{
    [self cleanUpAction];
}

- (NSMutableArray *)imageArr {
    if (!_imageArr) {
        _imageArr = [[NSMutableArray alloc] initWithObjects:image(@"gcy_icon_add_photo"), nil];
    }
    return _imageArr;
}
- (NSMutableArray *)imageUrlArray {
    if (!_imageUrlArray) {
        _imageUrlArray = [[NSMutableArray alloc] init];
    }
    return _imageUrlArray;
}

@end
